package com.xzh.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzh.model.Courses;
import com.xzh.model.search.CourseSearch;
import com.xzh.service.CourseService;
import com.xzh.util.JsonResult;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/courses")
public class CoursesApi {
    private CourseService coursesService;

    @Autowired
    public void setCoursesService(CourseService coursesService) {
        this.coursesService = coursesService;
    }

    @GetMapping
    public ResponseEntity<JsonResult<?>> selectAll(@RequestParam(defaultValue = "1") Integer pageNo,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   Courses  courses){
        Page<Courses> page = new Page<>(pageNo, pageSize);
        page = coursesService.selectAll(page, courses);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> add(@Valid @RequestBody Courses courses){
        boolean result = coursesService.save(courses);
        if ( result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("添加失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@Valid @RequestBody Courses courses){
        boolean result = coursesService.updateById(courses);
        if ( result){
            return ResponseEntity.ok(JsonResult.success());
        }else {
            return ResponseEntity.ok(JsonResult.fail("更新失败"));
        }
    }

    @DeleteMapping()
    public ResponseEntity<JsonResult<?>> delete(@RequestBody Integer[] ids){
        int count = this.coursesService.deleteByIds(List.of(ids));
        if( count == 0){
            return ResponseEntity.ok(JsonResult.fail("删除失败"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }
}
